
from rest_framework import serializers
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings

from .models import User, Address
from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU


class SKUSerializer(serializers.ModelSerializer):
    """用户浏览记录序列化器"""

    class Meta:
        model = SKU
        fields = ['id', 'name', 'price', 'default_image_url', 'comments']


class UserBrowsingHistorySerializer(serializers.Serializer):
    """用户浏览记录序列化器
    接受sku_id,校验sku_id,保存sku_id到redis
    """
    sku_id = serializers.IntegerField(label='商品ID', min_value=1)  # 1123456781

    def validate_sku_id(self, value):
        """
        校验sku_id
        :param value: sku_id
        :return: sku_id
        """
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('sku_id不存在')

        return value

    def create(self, validated_data):
        """
        重写create方法将sku_id到redis
        :param validated_data: {'sku_id':1}
        :return: validated_data
        """

        sku_id = validated_data.get('sku_id')
        user_id = self.context['request'].user.id

        # 创建连接到redis的对象
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()

        # 去重
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 添加
        pl.lpush('history_%s' % user_id, sku_id)
        # 截取
        pl.ltrim('history_%s' % user_id, 0, 4)
        # 执行
        pl.execute()

        return validated_data


class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    # 重写create方法，追加地址的外键的存储
    def create(self, validated_data):
        # user = validated_data['user']
        # 读取当前经过认证和权限的登录用户
        user = self.context['request'].user
        validated_data['user'] = user

        address = Address.objects.create(**validated_data)

        return address


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


class EmailSerializer(serializers.ModelSerializer):
    """添加邮箱序列化器"""

    class Meta:
        model = User
        fields = ['id', 'email']

        # 指定email为必传字段
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        """重写该方法：
        我们只对email进行存储
        后续还会在这里发送邮件：需要在更新数据成功之后，返回响应之前发送邮件
        instance ： 表示当前登录用户对象
        """
        instance.email = validated_data['email']
        instance.save()  # save()是ORM的方法

        # 获取邮箱激活链接
        # verify_url = generate_email_verify_url(user)
        verify_url = instance.generate_email_verify_url()

        # 更新完邮箱之后，处理响应之前，异步发送邮箱验证的邮件
        # send_verify_email() # 不会触发异步任务，相当于调用普通包中的普通函数而已
        send_verify_email.delay(instance.email, verify_url)

        return instance


class UserDetailSerializer(serializers.ModelSerializer):
    """对用户基本信息进行序列化"""

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class CreateUserSerializer(serializers.ModelSerializer):

    # 定义模型外部字段，
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    # 输出token
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        # 所有字段：'id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow'
        # 模型内部字段：'id', 'username', 'mobile', 'password'
        # 模型以外字段：'password2', 'sms_code', 'allow'
        # 输入字段(write_only)：'username', 'mobile', 'password', 'password2', 'sms_code', 'allow'
        # 输出字段(read_only)：'id', 'username', 'mobile'
        fields = ['id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow', 'token']

        # 给username和password指定额外参数
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 单个校验 validate_mobile validate_allow
    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        """验证勾选"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    # 联合校验 两次密码 短信验证码
    def validate(self, data):
        # 判断两次密码
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断短信验证码
        # 创建连接到redis对象
        redis_conn = get_redis_connection('verify_codes')
        mobile = data['mobile']
        # 从redis中获取验证码
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        # 判断是否存在
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        # 判断是否相同
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')
        return data

    # 重写序列化器的create方法：因为有些字段不能往数据库存
    def create(self, validated_data):
        """
        重写序列化器的create方法：因为有些字段不能默认往User里面存储
        :param validated_data: 经过校验之后的数据
        :return: user / 输出字段(read_only)：'id', 'username', 'mobile'
        """
        # 删除掉不需要存入User里的字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # 自己实现保存数据到User
        user = User.objects.create(**validated_data)

        # 调用django的认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 必须在注册或者登录之后，响应注册或者登录结果之前，生成jwt_token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 生成载荷：包含了user_id,username,email
        payload = jwt_payload_handler(user)

        # jwt_token
        token = jwt_encode_handler(payload)

        # 将token添加到user : python是面向对象的高级动态编程语言
        user.token = token

        # 响应数据（根据设计风格需返回user）
        # 输出字段(read_only)：'id', 'username', 'mobile', 'token'
        return user
